﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Offers.Models;

namespace ERPStore.Offers.Repositories
{
	public class SqlOfferRepository : CloudSoft.Repositories.SqlRepository<OffersDbContext>
		, IOffersRepository
	{
		public SqlOfferRepository()
		{

		}

		#region IOffersRepository Members

		public IQueryable<Models.OfferEx> GetOfferList()
		{
			var list = Query<Datas.OfferData>();
			var result = new List<Models.OfferEx>();
			foreach (var data in list)
			{
				var offer = data.ToOfferModel();
				result.Add(offer);
			}
			return result.AsQueryable();
		}

		public IQueryable<Models.OfferedProduct> GetOfferedProductList()
		{
			var list = Query<Datas.OfferedProductData>();
			var result = new List<Models.OfferedProduct>();
			foreach (var data in list)
			{
				var item = data.ToOfferedProductModel();
				result.Add(item);
			}
			return result.AsQueryable();
		}

		public void Save(Models.OfferEx offer)
		{
			var existing = Get<Datas.OfferData>(i => i.Id == offer.Id);
			var data = offer.ToOfferData();
			if (existing != null)
			{
				data.Id = existing.Id;
			}
			if (data.Id == 0)
			{
				Insert<Datas.OfferData>(data);
				offer.Id = data.Id;
			}
			else
			{
				Update<Datas.OfferData>(data);
			}
		}

		public void SaveOfferedProduct(Models.OfferedProduct offeredProduct)
		{
			var extData = Get<Datas.OfferedProductData>(i => i.Id == offeredProduct.Id);
			var data = offeredProduct.ToOfferedProductData();
			bool insert = false;
			if (extData == null)
			{
				extData = new Datas.OfferedProductData();
				insert = true;
			}

			extData.Discount = data.Discount;
			extData.FixedShippingPrice = data.FixedShippingPrice;
			extData.SaleFactor = data.SaleFactor;
			extData.SalePrice = data.SalePrice;
			extData.ShowStrikedPrice = data.ShowStrikedPrice;
			extData.ProductId = data.ProductId;
			extData.OfferId = data.OfferId;
			if (insert)
			{
				Insert<Datas.OfferedProductData>(extData);
				offeredProduct.Id = extData.Id;
			}
			else
			{
				Update<Datas.OfferedProductData>(extData);
			}
		}

		public IEnumerable<Models.OfferedProduct> GetOfferedProductListByOfferId(int offerId)
		{
			var list = Query<Datas.OfferedProductData>(i => i.OfferId == offerId);
			var result = new List<Models.OfferedProduct>();
			foreach (var item in list)
			{
				result.Add(item.ToOfferedProductModel());
			}
			return result;
		}

		public void DeleteOfferedProduct(Models.OfferedProduct offeredProduct)
		{
			var data = Query<Datas.OfferedProductData>(i => i.Id == offeredProduct.Id).Single();
			Delete<Datas.OfferedProductData>(data);
		}

		public void DeleteOffer(Models.OfferEx offer)
		{
			var data = Query<Datas.OfferData>(i => i.Id == offer.Id).Single();
			Delete<Datas.OfferData>(data);
		}

		#endregion
	}
}
